#!user/bin/env python3
# -- coding: utf-8 --
# @Createtime：2023/8/28 14:12
# @Updatetime：14:12
# @Author：Test008
# @File：3-CSS案例
# @Description：古诗文网站登录获取cookies，然后保存cookie，绕过登录到主页
import json
import time

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.implicitly_wait(5)
driver.get('https://www.gushiwen.cn/')
# 点击我的按钮
my_button = driver.find_element(By.CSS_SELECTOR, '.son1 a:nth-last-child(2)').click()
# 输入账号密码
email = driver.find_element(By.CSS_SELECTOR, '#email').send_keys('1478243841@qq.com')
pwd = driver.find_element(By.CSS_SELECTOR, '#pwd').send_keys('123456')
# 停留10秒，前端输入验证码，再点击登录
time.sleep(10)
denglu = driver.find_element(By.CSS_SELECTOR, '#denglu').click()
time.sleep(1)
cookie_dict = driver.get_cookies()
print(cookie_dict)
cookie_dict = json.dumps(cookie_dict)
with open('../static/json/loginCookie.txt', 'w', encoding='utf8') as file:
    file.write(cookie_dict)
time.sleep(2)
driver.quit()

# 重新登录
driver1 = webdriver.Chrome()
driver1.get('https://www.gushiwen.cn/')
with open('../static/json/loginCookie.txt', 'r', encoding='utf8') as file:
    cookie_data = file.read()

cookie_data = json.loads(cookie_data)
# 清除原有的cookie
driver1.delete_all_cookies()
for cookie in cookie_data:
    if 'expiry' in cookie.keys():
        cookie.pop('expiry')  # 清除过期信息

    driver1.add_cookie(cookie)

driver1.refresh()

time.sleep(3)

driver1.quit()
